package grape.workflow.rest.flowable.ext;

import cn.hutool.core.util.StrUtil;
import grape.workflow.rest.comment.mapper.CommentWebMapper;
import grape.workflow.service.comment.api.IWorkflowCommentService;
import grape.workflow.service.comment.dto.CommentDto;
import org.flowable.engine.impl.persistence.entity.CommentEntity;
import org.flowable.engine.task.Comment;
import org.flowable.engine.task.Event;
import org.flowable.idm.api.User;
import org.flowable.ui.task.service.runtime.FlowableCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by yangwei
 * Created at 2020/6/24 15:13
 */
@Service
public class CustomFlowableCommentService extends FlowableCommentService {
    @Autowired
    private IWorkflowCommentService iCommentService;
    @Autowired
    private CommentWebMapper commentWebMapper;
    @Override
    public Comment createComment(String message, User createdBy, String taskId, String processInstanceId) {
        //
        CommentDto commentDto = new CommentDto();
        commentDto.setFullMessage(message);
        if (StrUtil.isNotEmpty(message)) {
            String eventMessage = message.replaceAll("\\s+", " ");
            if (eventMessage.length() > 163) {
                eventMessage = eventMessage.substring(0, 160) + "...";
                commentDto.setMessage(eventMessage);
            }
        }
        commentDto.setUserId(createdBy.getId());
        commentDto.setTaskId(taskId);
        commentDto.setProcessInstanceId(processInstanceId);
        commentDto.setType(CommentEntity.TYPE_COMMENT);
        commentDto.setAction(Event.ACTION_ADD_COMMENT);
        CommentDto insert = iCommentService.insert(commentDto);
        return commentWebMapper.map(insert);
    }
}
